package org.cvcsc.weproject.repository;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.cvcsc.weproject.domain.AttendDetailStatus;
import org.cvcsc.weproject.domain.Attendance;
import org.cvcsc.weproject.domain.CourseSchedule;
import org.cvcsc.weproject.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;

@Component
public class ModelFinderImpl implements ModelFinder {
    @Autowired
    private AttendanceRepository attendanceRepository;
    @Autowired
    private StudentRepository studentRepository;
    @Autowired
    private ClazzRepository clazzRepository;
    @Autowired
    private StudentRepository tudentRepository;

    @Autowired
    private CourseScheduleRepository courseScheduleRepository;

    @Override
    public List<Student> findStudentsByClazzId(Long clazzId) {
        return this.studentRepository.findByClazzId(clazzId);
    }

    @Override
    public List<Attendance> findAllByWeekAndClazzId(int week,  Long clazzId) {
        return this.attendanceRepository
                .findByCourseSchedule_CourseScheduleTime_WeekAndCourseSchedule_Clazz_Id(
                        week,
                        clazzId);
    }

    @Override
    public Attendance getAttendanceWithScheduleClazzAndDetailsById(long id) {
        Attendance attendance = this.attendanceRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("未找到对应的考勤记录"));
        attendance.getCourseSchedule().getClazz();
        attendance.getDetails().forEach(d -> d.getStudent().getStudentNameAndNumber().getNumber());
        return attendance;
    }

    @Override
    public List<CourseSchedule> getCoursesByClazzId(long clazzId) {
        return this.courseScheduleRepository.findByClazzId(clazzId);
    }

    @Override
    public List<CourseSchedule> getCoursesByClazzId(int week,  Long clazzId) {
        return this.courseScheduleRepository.findByCourseScheduleTimeWeekAndClazzId(week,
                clazzId);
    }

    public Map<Long, AttendDetailStatus> getAttendancesDetailStatusOfGivenStudent(@Param("studentId") Long studentId) {
        List<Object[]> result = attendanceRepository.getAttendancesDetailStatusOfGivenStudent(studentId);
        Map<Long, AttendDetailStatus> map = result.stream()
                .map(item -> Map.entry((Long) item[0], (AttendDetailStatus) item[1])).collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue()));
        return map;
    }

}
